package com.freedy.concurrent.Monitors.sharingProblem;

import lombok.extern.slf4j.Slf4j;

/**
 * 共享所存在的问题
 * 解决->使用synchronized同步代码块
 * @author Freedy
 * @date 2021/4/20 22:35
 */
@Slf4j
public class Test2 {
    static int counter = 0;
    static final Object room = new Object();
    public static void main(String[] args) throws InterruptedException {
        int abc = 0;
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (room) {
                    counter++;
                }
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (room) {
                    counter--;
                }
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}",counter);
    }
}
